package com.liang.springbatch.config;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.core.step.builder.TaskletStepBuilder;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName JobConfiguration
 * @Description TODO
 * @Author liang
 * @Date 2019/5/30 21:53
 * @Version 1.0
 **/
@Configuration
@EnableBatchProcessing
public class JobConfiguration2 {
    //创建任务对象的对象
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    //任务的执行由Step决定
    //注入创建step对象的对象
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    //创建任务对象
    @Bean
    public Job helloSpringBatch(){
        return jobBuilderFactory.get("第二个job")
                //.start(step1())
                //.next(step2())
                .start(step1())
                .on("COMPLETED").to(step2())
                .from(step2()).end()
                .build();
    }

    @Bean
    public Step step2() {

        StepBuilder stepBuilder = stepBuilderFactory.get("第二个job的step2");
        //两种方式,tasklet 或 Chunk
        TaskletStepBuilder tasklet = stepBuilder.tasklet(new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                //任务执行的内容
                System.out.printf("执行  第二个job的step2    ... ");
                //返回状态值
                return RepeatStatus.FINISHED;
            }
        });
        return tasklet.build();
    }

    @Bean
    public Step step1(){
        StepBuilder stepBuilder = stepBuilderFactory.get("第二个job的step1");
        //两种方式,tasklet 或 Chunk
        TaskletStepBuilder tasklet = stepBuilder.tasklet(new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
                //任务执行的内容
                System.out.printf("执行第二个job的step 1... ");
                //返回状态值
                return RepeatStatus.FINISHED;
            }
        });
        return tasklet.build();
    }
}
